$(function () {
    // 初始化富文本编辑器
    initEditor()
    renderSelect()
    // 初始化下拉选择框
    function renderSelect() {
        var layer = layui.layer
        var form = layui.form
        $.ajax({
            type: "GET",
            url: '/article/category',
            success: function (res) {
                console.log(res.data);
                let tmphtml = template("tpl-cate", res)
                $('[name=cate_id]').html(`${tmphtml}`)
                form.render()
            }
        })
    }
    // 封面裁剪
    // 1. 初始化图片裁剪器
    var $image = $('#image')

    // 2. 裁剪选项
    var options = {
        aspectRatio: 300 / 400,
        preview: '.img-preview'
    }

    // 3. 初始化裁剪区域
    $image.cropper(options)

    // 点击文件上传
    $('#choicecover').on('click', function (e) {
        e.preventDefault()
        $('#choicefile').click()
        // 监听上传文件
    })
    $('#choicefile').on('change', function (e) {
        let files = e.target.files
        if (files.length < 0) {
            return
        }
        let newImgURL = URL.createObjectURL(files[0])
        $image.cropper("destroy").attr('src', newImgURL).cropper(options)
    })
    let isrelease = 1
    $('#btnSave').on('click', function (e) {
        e.preventDefault()
        isrelease = 0
    })
    $('#form-data').on('submit', function (e) {
        e.preventDefault()
        console.log($(this)[0]);
        let data = {}
        data.articletitle = $('#articletitle').val()
        data.category = $('#scategory').val()
        data.articlecontent = $('#articlecontent').val()
        // 4. 将封面裁剪过后的图片，输出为一个文件对象
        data.articleimg = $image
            .cropper('getCroppedCanvas', {
                // 创建一个 Canvas 画布
                width: 300,
                height: 400
            })
            .toDataURL('image/png')
        data.isrelease = isrelease
        data.token = sessionStorage.getItem('token')
        $.ajax({
            type: "POST",
            url: "/article/addarticle",
            data,
            success: function (res) {
                console.log(res);
            }
        })
    })

})